import {
  login,
  secondLogin,
  logout,
  getInfo,
  refreshToken,
  thirdLogin,
  thirdTaiyueLogin,
  firstCheckPwd,
} from "@/api/login";
import { setTokenEncrypt, removeToken } from "@/utils/auth";
import { getUserPic } from "@/api/person";

import { dept_select } from "@/api/management/usercenter/user.js";

const user = {
  state: {
    token: "",
    name: "",
    nickName: "",
    isFirstLogin: "",
    avatar: "",
    roles: [],
    permissions: [],
    department: [],
    isAdmin: false,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_NICK_NAME: (state, nickName) => {
      state.nickName = nickName;
    },
    SET_IS_FIRST_LOGIN: (state, isFirstLogin) => {
      state.isFirstLogin = isFirstLogin;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_ROLE_IDS: (state, roleIds) => {
      state.roleIds = roleIds;
    },
    SET_IS_ADMIN: (state, isAdmin) => {
      state.isAdmin = isAdmin;
    },
    SET_DEPARTMENT: (state, department) => {
      if (department && department instanceof Array) {
        state.department = department;
      } else {
        state.department = [];
      }
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const userName = userInfo.userName.trim();
      const password = userInfo.password;
      const verifyCode = userInfo.verifyCode;
      const verifyCodeUuid = userInfo.verifyCodeUuid;
      return new Promise((resolve, reject) => {
        login(userName, password, verifyCode, verifyCodeUuid, userInfo.flag)
          .then((res) => {
            if (res && res.rescode === 200) {
              let data = res.data;
              // let timestamp=new Date().getTime()
              // setTokenEncrypt(timestamp);
              if (data.resultCode == "0") {
                //无须二次验证
                setTokenEncrypt(data.token);
              }
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 亚信4A 第三方平台登录
    ThirdLogin({ commit }, userInfo) {
      const token = userInfo.token;
      const appAcctId = userInfo.appAcctId;
      return new Promise((resolve, reject) => {
        thirdLogin({ token: token, appAcctId: appAcctId })
          .then((res) => {
            if (res && res.code === 200) {
              let data = res.data;
              if (data.secondaryLoginPolicyId == "1") {
                //无须二次验证
                setTokenEncrypt(data.token);
              }
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 泰岳4A 第三方平台登录
    ThirdTaiyueLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        thirdTaiyueLogin()
          .then((res) => {
            if (res && res.code === 200) {
              let data = res.data;
              if (data.secondaryLoginPolicyId == "1") {
                //无须二次验证
                setTokenEncrypt(data.token);
              }
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 二次登录
    secondLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        secondLogin(userInfo)
          .then((res) => {
            let data = res.data;
            if (
              data.secondaryLoginPolicyId !== "2" ||
              data.secondaryLoginPolicyId !== "3"
            ) {
              setTokenEncrypt(data.token);
            }
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 验证密码是否符合密码规则
    firstCheckPwd({ commit }, userInfo) {
      const userName = userInfo.userName.trim();
      const password = userInfo.password;
      const verifyCode = userInfo.verifyCode;
      const verifyCodeUuid = userInfo.verifyCodeUuid;
      return new Promise((resolve, reject) => {
        firstCheckPwd(userName, password, verifyCode, verifyCodeUuid)
          .then((res) => {
            if (res && res.code === 200) {
              // commit("SET_PASSWORD_RULE", res.data);
              resolve(res);
            } else {
              // commit("SET_PASSWORD_RULE", res.data);
              reject(res);
            }
          })
          .catch((error) => {
            // commit("SET_PASSWORD_RULE", 0);
            reject(error);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const user = res.user;

            if (user.avatar) {
              getUserPic(user.avatar)
                .then((res) => {
                  if (res && res.code === 200) {
                    if (res.data) {
                      commit("SET_AVATAR", `data:image/png;base64,${res.data}`);
                    } else {
                      commit("SET_AVATAR", null);
                    }
                  } else {
                    commit("SET_AVATAR", null);
                  }
                })
                .catch((err) => {
                  commit("SET_AVATAR", null);
                });
            } else {
              commit("SET_AVATAR", null);
            }

            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit("SET_ROLES", res.roles);
              commit("SET_PERMISSIONS", res.permissions);
            } else {
              commit("SET_ROLES", ["ROLE_DEFAULT"]);
            }
            commit("SET_NAME", user.userName);
            commit("SET_NICK_NAME", user.nickName);
            commit("SET_IS_FIRST_LOGIN", res.isFirstLogin);
            commit("SET_ROLE_IDS", user.roleIds);
            commit("SET_IS_ADMIN", res.superAdmin);
            commit("SET_DEPARTMENT", user.deptIdArr);

            if (
              res.isForceUpdatePwd === 0 &&
              window.sp_config.CURRENT_THIRD_LOGIN_VENDOR === "0"
            ) {
              return reject();
            }

            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 刷新token
    RefreshToken({ commit, state }) {
      return new Promise((resolve, reject) => {
        refreshToken(state.token)
          .then((res) => {
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            resolve();
          })
          .catch((error) => {
            reject(error);
          })
          .finally(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
          });
      });
    },

    clearLoginStatus({ commit, state }) {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_PERMISSIONS", []);
      removeToken();
    },

    /**
     * 清除用户信息 用于异地登录被挤下线的场景
     * @param commit
     * @param state
     * @returns {Promise<unknown>}
     */
    clearUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        commit("SET_PERMISSIONS", []);
        removeToken();
        resolve();
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
